package net.lulihu.common_util.jdbc;

import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * 默认数据源初始化程序
 */
public class DefaultDataSourceOperational implements DataSourceOperational {

    @Override
    public DataSource initDataSource(DatabaseConfig config) {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setPoolName(config.getPoolName());
        hikariDataSource.setJdbcUrl(config.getUrl());
        hikariDataSource.setDriverClassName(config.getDriverClassName());
        hikariDataSource.setUsername(config.getUsername());
        hikariDataSource.setPassword(config.getPassword());
        hikariDataSource.setMaximumPoolSize(config.getMaxActive());
        hikariDataSource.setMinimumIdle(config.getMinIdle());
        hikariDataSource.setConnectionTimeout(config.getConnectionTimeout());
        hikariDataSource.setIdleTimeout(config.getIdleTimeout());
        hikariDataSource.setMaxLifetime(config.getMaxLifetime());
        hikariDataSource.setConnectionTestQuery(config.getConnectionTestQuery());
        return hikariDataSource;
    }

    @Override
    public void close(DataSource dataSource) {
        if (dataSource instanceof HikariDataSource) {
            ((HikariDataSource) dataSource).close();
        }
    }


}
